import { app } from 'electron'
import icon from '../../resources/logo.png?asset'
import { getAppExitManager } from './modules/app/appExit'
import { getAuthManager, createAuthConfig } from './modules/manager/authManager'
import { getMenuManager } from './modules/manager/dockTrayManager'
import { getIPCManager } from './modules/manager/ipcManager'
import { getWindowFactory, createWindowCreators } from './modules/windowFactory'
import { getThemeManager } from './modules/manager/themeManager'
import { createAppLauncher, AppConfig, ManagerInstances } from './modules/app/appInitializer'
import { PreviewWindowManager } from './modules/manager/previewWindowManager'
import { getNotificationManager } from './modules/manager/notificationManager'

// 应用配置
const appConfig: AppConfig = {
  basic: {
    name: 'XLChat',
    version: '1.0.0',
    description: '基于Vue3+Electron IM即时通讯',
    author: 'LYC'
  },
  window: {
    loginWidth: 320,
    loginHeight: 580,
    mainWidth: 1000,
    mainHeight: 700,
    minWidth: 800,
    minHeight: 600
  },
  icon: icon // 使用通过import导入的图标资源
}

// 初始化所有管理器
const exitManager = getAppExitManager()
const menuManager = getMenuManager(exitManager)
const ipcManager = getIPCManager()
const windowFactory = getWindowFactory(exitManager)
const themeManager = getThemeManager()
const notificationManager = getNotificationManager()
const previewWindowManager = new PreviewWindowManager()

// 预创建认证配置（稍后添加回调）

// 创建窗口创建器
const windowCreators = createWindowCreators(
  exitManager,
  {
    LOGIN_WIDTH: appConfig.window.loginWidth,
    LOGIN_HEIGHT: appConfig.window.loginHeight,
    MAIN_WIDTH: appConfig.window.mainWidth,
    MAIN_HEIGHT: appConfig.window.mainHeight,
    MIN_WIDTH: appConfig.window.minWidth,
    MIN_HEIGHT: appConfig.window.minHeight
  },
  icon,
  {
    setLoginWindow: () => {
      // 在回调中不需要保存引用，由窗口管理器负责处理
      console.log('登录窗口已创建')
    },
    setMainWindow: () => {
      // 在回调中不需要保存引用，由窗口管理器负责处理
      console.log('主窗口已创建')
    }
  }
)

// 创建认证配置，添加窗口创建回调
const authConfigWithCallbacks = createAuthConfig(
  appConfig.window.loginWidth,
  appConfig.window.loginHeight,
  appConfig.window.mainWidth,
  appConfig.window.mainHeight,
  appConfig.window.minWidth,
  appConfig.window.minHeight,
  windowCreators
)

// 初始化认证管理器
const authManager = getAuthManager(authConfigWithCallbacks)

// 管理器实例集合
const managers: ManagerInstances = {
  exitManager,
  authManager,
  menuManager,
  ipcManager,
  windowFactory,
  themeManager,
  notificationManager
}

// 初始化预览窗口管理器
previewWindowManager.initialize()

// 配置macOS dock图标
if (process.platform === 'darwin' && app.dock) {
  app.dock.setIcon(icon)
}

// 创建应用启动器
const appLauncher = createAppLauncher(appConfig)
const launchApp = appLauncher(managers, windowCreators)

// 启动应用
launchApp().catch((error) => {
  console.error('Failed to launch application:', error)
  process.exit(1)
})
